﻿using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using LevelEditor.Document;
using LevelEditor.Forms;
using System.Windows.Forms;

namespace LevelEditor.View
{
    public class DoUndoLayerResize : DoUndoNothing
    {
        #region Fields

        int LayerIndex;

        Size DoSize;

        Size UndoSize;

        List<KeyValuePair<Point, Tile>> UndoTiles;

        #endregion

        #region Constructors

        public DoUndoLayerResize(MainForm form, int layerIndex, Size size):base(form)
        {
            Layer Layer = form.Level.Layers[LayerIndex];
            LayerIndex = layerIndex;
            DoSize = size;
            UndoSize = Layer.Size;
            if (DoSize.Width < UndoSize.Width || DoSize.Height < UndoSize.Height)
                UndoTiles = new List<KeyValuePair<Point, Tile>>();
            foreach(KeyValuePair<Point, Tile> pair in Layer.Tiles)
            {
                if (pair.Key.X >= Layer.Size.Width ||
                    pair.Key.Y >= Layer.Size.Height)
                    UndoTiles.Add(pair);
            }
        }

        #endregion

        #region Methods

        public override bool Do()
        {
            Cursor.Current = Cursors.WaitCursor;
            Layer Layer = MainForm.Level.Layers[LayerIndex];
            Layer.Size = DoSize;
            foreach (KeyValuePair<Point, Tile> pair in UndoTiles)
            {
                Layer.Tiles.Remove(pair.Key);
            }
            MainForm.LayerViewControl.LayerSizeChanged();
            MainForm.LayerViewControl.Invalidate();
            Cursor.Current = Cursors.Default;
            return base.Do();
        }

        public override void Undo()
        {
            Cursor.Current = Cursors.WaitCursor;
            Layer Layer = MainForm.Level.Layers[LayerIndex];
            Layer.Size = UndoSize;
            foreach (KeyValuePair<Point, Tile> pair in UndoTiles)
            {
                Layer.Tiles.Add(pair.Key, pair.Value);
            }
            MainForm.LayerViewControl.LayerSizeChanged();
            MainForm.LayerViewControl.Invalidate();
            Cursor.Current = Cursors.Default;
        }

        public override string ToString()
        {
            return "Layer " + LayerIndex.ToString() + " resized";
        }

        #endregion
    }
}
